var express = require('express');
var bodyParser = require('body-parser');
var cors = require('cors');
var md5 = require('nodejs-md5');
var conn = require('./mysqlServer');

// const alipaySdk = require('../js/alipay')

const AlipaySdk = require('alipay-sdk').default;;
// const fs = require("fs");
const AlipayFormData = require("alipay-sdk/lib/form").default;

const alipaySdk = new AlipaySdk({
  appId: '2021000117606721', // 开放平台上创建应用时生成的 appId
  // privateKey: fs.readFileSync('../config/pem/app_private_key.pem', 'ascii'),
  privateKey: 'MIIEowIBAAKCAQEAgo+oDztnFhwcvqjJpImWtQA7gXIJtPL9AMwSbZUFi1TJOYTFf2ZVWE1NBrvIIVw45/DF+S/GwzZtwVVYNr3fm1t8L9/cnJYcxTsL+vM6kOW9qI+0dN75g/yV7KYnXk+7M66mGZdbfBqAXaamXRX2LyVMN1FBAKUfXLKoSxkAIgEhkn5Es+fT5tNiGYuGTtg+F+bXRqLUvsZRIUfQWKgnUOMWqJeOS1qtWTTaOEBmQ4tzJ9ZpUVMdW4T2AMri/0lVAcm0in7YChDFqOGqYZ7dy5VBgx2UBb8nBts1ydJE4afUJkx5TOel//reTCpsskO6+/1BlV52Sq2wIZvv91S7SQIDAQABAoIBAHPTNeitbjpzHh0WaCyL0yMn3aJspKfemQzH/eExPwXoZcudOghXpIb9rMO4e0b9JY6+TyNNeytbcer955BIycJtWrKuCmzvzv4579rlRKOe7K5JLnIwDXNF9UtH680DNrQW0EwLtqFWcWKjoRsbjJcuo3q/nscPtc7qv9o/h5qhzTZYn5zVEe73PA8EGgNne9MfBsM3nRIqjECLvmgR0loNGwSfbJzb3dfy9y/U0JOGFRB+rnNs+NNvTBR8uX5pBnNUp8lQXKeSHPt4jVcd8TmszDM9GexQ+ZyhYhlL9a++gQL7U5/GukQDgqEjIH8jcYeQ0kgesfkVzkRr5H8jCXECgYEA8Y6Qe0eNlRbIn+Q3qmjwHy8MF9I1joV+mYzC0xTC+1NrMEJzyMUspQIAsRhnqtc6Y9MsDax93QnM2goykRWlCSz+Hiuhl5DpMPZx5rb1H9TtrJpdz9fzjLcS6+LaHaF2xVhD7F4WZ38/J+QxdPzgCFT/FGAtKGEIPdZZORffrysCgYEAil4dfaowBAD7gqbkru9kss8ppPAXrO7VRup8pUFtrUkC7fuAfy2NAXj2sj6HIYEtChaigeOo78rXRKZClybesi1EgI6zGJk3D1g3wKOD9h1FMGlDT2aVWOilpnHoE9NGLA2LDIFcqC8ySXONzhRx+pG02NJGjblsfW7YpZlg5VsCgYEAp2FGNGZscPaMpl6ZQ/fbC4CqPIdonQ1boEKtbV5hjY1MJPCnEmOuf9hXal+i1fq1dx6I1CDGRjfYPu36BBafeTA4Fefd3QyIyWi7nEcCq7/7wTJl9vOIy+S/s7xJr2aGylBTIKJBnA3MUXQJ4Sqogp2C8zeBkw1JjK/Ou4UTdmkCgYAvexZRngn2BcRI1C5bHUkH1vDqaX0mWZqUSDjXmHkjYo9/zLMOcToWzESTa8OBKsuiz5uaSN4a0xdFtmvZZHw81i3Qk6c/hKwRNuuCzlmlJewtLaHsaD5NkR/u2t2RmAlXappRgz6hc/ikneOGWRu3qTJOyPFvBrcE3/m18cj/SwKBgD8v82SRsIdt5axGTGKq49UsvFW/VLmB0jXoTFXnc1fa0tGHHi9XWpJh6jCEKGeHFzPrMQYg/IdV/+KAjtLLZf4zcaue6+XxjfPx/61fD59qE6dclO1txNBK6LSJ6MpU5y+UnTA7nvRUe6jqESwi8Zr/9SYOEMwt9sOSXMxXdD4g',
  gateway: 'https://openapi.alipaydev.com/gateway.do',// 支付宝网关地址 ，沙箱环境下使用时需要修改
  // alipayPublicKey: fs.readFileSync('../config/pem/alipay_public_key.pem', 'ascii'),
  alipayPublicKey: 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA5oleCG23KGMJStjceXmund6fkDij1r6AnomqWTlpYFvpvNZci8QkuLZ09KcpmrWlX82vMWwYu92MdtoMfn4To7F/FkCUyc7RbXKM67BfeL8jf2kEDL4adYZqKb35KLctIbQpfPyuxtbleD1Br2eBh9xeYvK5excI3+rTL8pheD4O8J8OAliXJra2UGz8svv6qTHg4TtQbx23/Q781GNm0E/m1YWZLhHlpP92A/yXIDdBi+/sz/kogiVwxL9F6JxtGtNTeM0CjBoQC93yTC5/v2PNiSAy/2T4j1SJdm4lbAKYnjmZUAUTd9gM0RIMwlndKWZ7ZzgEOO9sKxNvCSOl2wIDAQAB',
  signType: 'RSA2' // 签名算法,默认 RSA2
});

var app = express();
app.use(bodyParser.urlencoded({extended:false}));
app.use(cors());

app.post('/jj',async (req, res) => {
    console.log(req.body);
    var no=new Date().getTime();
    var time = encodeURIComponent(req.body.time);
    var money = req.body.money?req.body.money:0;
    const formData = new AlipayFormData();
  
    formData.addField('returnUrl', 'http://localhost:8080/home');//支付成功之后跳转的页面
    formData.addField('quitUrl', 'http://localhost:8080/onlinePay');//退出支付后跳转的页面
    formData.addField('bizContent', {
    outTradeNo: req.body.time+'_'+no+"_"+money,
    productCode: 'FAST_INSTANT_TRADE_PAY',
    totalAmount: req.body.price+'.00',
    subject: req.body.subject,
    passbackParams:time,
    body: '商品详情',
    });
  
   const result = await alipaySdk.exec(
     'alipay.trade.wap.pay',
     {},
     { formData: formData },
   );
  
    // result 为 form 表单
    console.log(result);
  
    // result 为 form 表单
    console.log(result);
    res.send(result);
  
})


app.post('/login',function(req,res,next){
  conn.query(`select * from user where username=?`,[req.body.username],function(err,result){
    if(err){
      res.send(JSON.stringify({code:500,err:'服务器错误'}))
    }else{
      if(result.length > 0){
        if(result[0].password == req.body.password){
          let num = Math.floor(Math.random()*1000);
          md5.string.quiet(req.body.username+num,function(err,md5Str){
          if(err){
            console.log('加密失败');
          }else{
            conn.query(`insert into token set ?`,{token:md5Str},function(err){
              if(err){
                console.log('存入失败');
              }else{
                res.send(JSON.stringify({code:200,msg:'登录成功',to:md5Str,result}));
              }
            })
          }
        })
        }else{
          res.send(JSON.stringify({code:400,msg:'密码错误'}));
        }
      }else{
        res.send(JSON.stringify({code:404,msg:"账号不存在，请注册"}));
      }
    }
  })
});

app.post('/regist',function(req,res,next){
  conn.query(`select * from user where username = ?`,[req.body.username],function(err,result){
    if(err){
      res.send(JSON.stringify({code:500,msg:"服务器内部错误"}))
    }else{
      if(result.length>0){
        res.send(JSON.stringify({code:404,msg:"用户名已存在，请重新输入"}));
      }else{
        conn.query(`insert into user set ?`,{username:req.body.username,password:req.body.password},function(err,result){
          if(!err){
            res.send(JSON.stringify({code:200,msg:"注册成功！"}));
          }
        })
      }
    }
  })
});

//修改密码
app.post('/update',function(req,res,next){
  conn.query('select password from user where username = ?',[req.body.zhanghao],function(err,result){
    if(err){
      res.send(JSON.stringify({code:500,msg:'服务器内部错误'}));
    }else{
      // console.log(result);
      // console.log(req.body.oldP);
      if(req.body.oldP == result[0].password){
        // console.log('sss')
        if(req.body.newP == req.body.newP1){
          conn.query('update user set password = ? where username=?',[req.body.newP,req.body.zhanghao],function(err,result){
            if(!err){
              res.send(JSON.stringify({code:200,msg:'密码修改成功'}));
            }
          })
        }else{
        res.send(JSON.stringify({code:400,msg:'两次密码输入不一致'}))
        }
      }else{
        res.send(JSON.stringify({code:404,msg:'旧密码输入错误'}))
      }
    }
  })
})

app.post('/confirm',function(req,res,next){
  conn.query(`select * from token where token = ?`,[req.body.token],function(err,result){
    if(err){
      console.log('错误');
    }else{
      if(result.length == 0){
        res.send(JSON.stringify({code:404,msg:'未登录！'}));
      }else{
        res.send(JSON.stringify({code:200,msg:'已登录！'}));
      }
    }
  })
})

app.listen(8081);

